from flask import Flask, jsonify, render_template, request
from flask_sqlalchemy import SQLAlchemy
from flask_redis import FlaskRedis
import pymysql

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root:123456@127.0.0.1:3306/dwz"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

db = SQLAlchemy(app)
redis_store = FlaskRedis(app)

CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"


class Store(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    token = db.Column(db.String(7), index=True)
    url = db.Column(db.String(256), unique=True)


def encode(num):
    if num == 0:
        return CHARS[0]
    res = []
    while num:
        num, rem = divmod(num, len(CHARS))
        res.append(CHARS[rem])
    return ''.join(reversed(res))


@app.route('/shorten', methods=['POST'])
def short_url():
    long_url = request.json['url']
    if not long_url:
        return jsonify(url="请输入长网址，输入不能为空！")
    if Store.query.filter_by(url=long_url).all():
        return jsonify(url="您输入的网址已经存在，请重新输入！")
    index = int(redis_store.incr('CNT'))
    token = encode(index)
    store = Store(token=token, url=long_url)
    db.session.add(store)
    db.session.commit()
    short_url = 'https://YX.com/' + token
    return jsonify(url=short_url)


@app.route('/')
def index():
    return render_template('index.html')


if __name__ == "__main__":
    app.run(debug=True)
